﻿const cloud = require("wx-server-sdk");

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });

const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

const queryFinishedRegisteredActivities = async event => {
  const wxContext = cloud.getWXContext();
  const openID = wxContext.OPENID;

  if (!openID) {
    return { success: false, error: "未获取到用户信息" };
  }

  const pageSize = 10;
  const tableRaw = Number(event && event.tableNumber);
  const tableNumber = Number.isFinite(tableRaw) && tableRaw > 0 ? Math.floor(tableRaw) : 1;
  const skip = (tableNumber - 1) * pageSize;
  const now = new Date();

  try {
    const aggregateRes = await db
      .collection("Group_Registration_Information")
      .aggregate()
      .match({ OpenID: openID })
      .lookup({
        from: "Activity_Group_Information",
        localField: "GroupID",
        foreignField: "_id",
        as: "group"
      })
      .unwind("$group")
      .lookup({
        from: "Activity_Information",
        localField: "group.ActivityID",
        foreignField: "_id",
        as: "activity"
      })
      .unwind("$activity")
      .match({
        "activity.Status": _.in(["Published", "Withdraw"])
      })
      .group({
        _id: "$group.ActivityID",
        latestEndTime: $.max("$group.GroupEndTime"),
        activityName: $.first("$activity.ActivityName"),
        activityImage: $.first("$activity.ActivityImageURL"),
        activityLocation: $.first("$activity.ActivityLocation"),
        registrationTime: $.max("$RegistrationTime")
      })
      .match({
        latestEndTime: _.and(_.neq(null), _.lt(now))
      })
      .sort({
        registrationTime: -1
      })
      .skip(skip)
      .limit(pageSize)
      .end();

    const finishedList = (aggregateRes && aggregateRes.list) || [];
    if (finishedList.length === 0) {
      return { success: true, activities: [] };
    }

    const activityIDs = finishedList.map(item => item._id);
    const groupsRes = await db
      .collection("Activity_Group_Information")
      .where({ ActivityID: _.in(activityIDs) })
      .field({ ActivityID: 1, GroupStartTime: 1 })
      .get();

    const startTimesMap = new Map();
    (groupsRes.data || []).forEach(group => {
      if (!group || !group.ActivityID) return;
      const list = startTimesMap.get(group.ActivityID) || [];
      if (group.GroupStartTime) {
        list.push(group.GroupStartTime);
      }
      startTimesMap.set(group.ActivityID, list);
    });

    const activities = finishedList.map(item => ({
      activityID: item._id,
      activityName: item.activityName || "",
      activityImage: item.activityImage || "",
      activityStartTime: startTimesMap.get(item._id) || [],
      activityLocation: item.activityLocation || ""
    }));

    return { success: true, activities };
  } catch (error) {
    console.error("queryFinishedRegisteredActivities error", error);
    return {
      success: false,
      error: (error && error.message) || "查询已结束的参与活动失败"
    };
  }
};

exports.main = async (event, context) => {
  return queryFinishedRegisteredActivities(event);
};

